<script setup>
import { fetchGoodsList, deleteGoods } from '@/api/goods'
import { onMounted, ref } from 'vue'
import AddGoods from './components/AddGoodsInfo.vue'
import logger from '@/utils/logger'
import ViewHTML from '@/components/ViewHTML.vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const currentGoods = ref(null)
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const previewVisible = ref(false)
const previewContent = ref('')

const queryFields = ref({
  goodsName: '',
  dealerGoodsTypeName: '',
})

const openAddDialog = () => {
  currentGoods.value = null
  dialogVisible.value = true
}

const openEditDialog = (row) => {
  // 创建一个深拷贝，避免直接操作原数据
  currentGoods.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const fetchGoodsData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        goodsName: queryFields.value.goodsName.trim() || null,
        dealerGoodsTypeName: queryFields.value.dealerGoodsTypeName.trim() || null,
      },
    }
    const res = await fetchGoodsList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    logger.error('获取商品列表失败', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 删除商品 - 使用el-popconfirm组件替代此方法
const handleDeleteDirect = async (id) => {
  try {
    loading.value = true
    const res = await deleteGoods(id)
    if (res.success) {
      ElMessage.success('删除成功')
      await fetchGoodsData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    logger.error('删除商品失败', error)
    ElMessage.error('删除商品失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGoodsData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGoodsData()
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  fetchGoodsData()
}

// 重置搜索条件
const resetSearch = () => {
  queryFields.value.goodsName = ''
  currentPage.value = 1
  fetchGoodsData()
}

// 预览商品介绍
const previewIntroduce = (content) => {
  previewContent.value = content
  previewVisible.value = true
}

onMounted(() => {
  fetchGoodsData()
})
</script>
<template>
  <el-dialog
    v-model="previewVisible"
    title="商品介绍预览"
    width="40%"
    align-center
    destroy-on-close
  >
    <ViewHTML :content="previewContent" />
  </el-dialog>

  <el-dialog
    v-model="dialogVisible"
    :title="currentGoods ? '编辑商品' : '添加商品'"
    width="800px"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoods :initial-data="currentGoods" @success="fetchGoodsData" @close="closeDialog" />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="queryFields">
          <el-form-item label="商品名称">
            <el-input
              v-model="queryFields.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品类别">
            <el-input
              v-model="queryFields.dealerGoodsTypeName"
              placeholder="请输入商品类别"
              clearable
              style="width: 190px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            添加商品
          </el-button>
        </el-form-item>
      </div>
    </div>
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          show-overflow-tooltip
          label="商品名称"
          min-width="150"
          align="center"
        />
        <el-table-column label="商品类别" min-width="150" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.dealerGoodsTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.specifications }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column
          prop="introduce"
          label="商品介绍"
          min-width="150"
          :show-overflow-tooltip="true"
          align="center"
        >
          <template #default="{ row }">
            <div class="intro-column">
              <el-button
                v-if="row.introduce"
                type="primary"
                size="small"
                link
                @click="previewIntroduce(row.introduce)"
              >
                <template #icon>
                  <el-icon><LineMdWatchLoop /></el-icon>
                </template>
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产地" min-width="120" :show-overflow-tooltip="true" align="center">
          <template #default="{ row }"> {{ row.address }} </template>
        </el-table-column>
        <el-table-column label="停售状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isDiscontinued === 1 ? 'danger' : 'success'">
              {{ row.isDiscontinued === 1 ? '停售' : '在售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>
            <el-popconfirm
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除商品 '${row.goodsName}' 吗？`"
              width="250"
              confirm-button-type="danger"
              @confirm="handleDeleteDirect(row.dealerGoodsId)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;

    .el-table {
      flex: 1;
    }
    .no-image {
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      background-color: #f5f7fa;
      font-size: 12px;
      border-radius: 4px;
      border: 1px dashed #d9d9d9;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}

// 介绍列布局
.intro-column {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}
</style>
